package com.fl.niu.bo;

import com.fl.niu.model.Admin;
import com.fl.niu.model.AdminPermission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SpringSecurity需要的用户详情
 * @author admin
 */
public class AdminUserDetails implements UserDetails {
    private Admin umsAdmin;
    private List<AdminPermission> umsPermissions;
    public AdminUserDetails(Admin umsAdmin, List<AdminPermission> umsPermissions) {
        this.umsAdmin = umsAdmin;
        this.umsPermissions = umsPermissions;
    }

    /**
     * 用于hasAuthority实现权限控制
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //返回当前用户的权限
        return umsPermissions.stream()
                .filter(permission -> permission.getValue() != null)
                .map(permission -> new SimpleGrantedAuthority(permission.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return umsAdmin.getPassword();
    }

    @Override
    public String getUsername() {
        return umsAdmin.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return umsAdmin.getStatus().equals(1);
    }

    public Admin getUmsAdmin() {
        return umsAdmin;
    }

    public void setUmsAdmin(Admin umsAdmin) {
        this.umsAdmin = umsAdmin;
    }
}
